package com.zyk.scaffold.tcp.session;

import io.netty.channel.ChannelHandlerContext;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class SessionStore {
    protected Map<String, Session> sessions = new ConcurrentHashMap<String, Session>();
    public void addSession(Session session) {
        if (null == session) {
            return;
        }
        sessions.put(session.getId(), session);
    }

    public void updateSession(String sessionId) {
        Session session = sessions.get(sessionId);
        session.setLastAccessedTime(LocalDateTime.now());
        sessions.put(sessionId, session);
    }

    public void removeSession(Session session) {
        if (session == null) {
            throw new IllegalArgumentException("session is null!");
        }
        removeSession(session.getId());
    }

    public void removeSession(String sessionId) {
        sessions.remove(sessionId);
    }

    public Session getSession(String sessionId) {
        return sessions.get(sessionId);
    }

    public Session[] getSessions() {
        return sessions.values().toArray(new Session[0]);
    }

    public Set<String> getSessionKeys() {
        return sessions.keySet();
    }

    public int getSessionCount() {
        return sessions.size();
    }

    public void refreshHeartbeat(String sessionId, ChannelHandlerContext ctx) {
        Session session = sessions.get(sessionId);
        session.refreshLastAccessedTime();
        session.getConnection().refreshChannelHandlerContext(ctx);
    }
}
